<script lang="ts" setup>
import { ref, computed, watch, onMounted, reactive, PropType } from 'vue';
import AddMetricsDemand from '../addMetricsDemand/index.vue';
import DemandForm from '../demandForm/index.vue';
import ATabsCard from '../aTabsCard/index.vue';
import { Message, Modal } from '@arco-design/web-vue';
import API from '@/services';
import {debounce, cloneDeep} from 'lodash'
const visible = ref<boolean>(false)
const props = defineProps({
  title: {
    type: String,
  },
  editData: {
    type: Object as PropType<any>
  },
})
interface FormValueI {
  demandName: String | undefined;
  priorityLevel: String | undefined;
  description: String | undefined;
}
interface MetricsFormI {
    demandName: String | undefined;
    metricsLevel: String | undefined;
    description: String | undefined;
    supportDimension: String | undefined;
    remarks: String | undefined;
    timePeriod: String | undefined,
}
let formValue = reactive<{value:FormValueI}>({
  value: {
    demandName: '',
    priorityLevel: '',
    description: ''
  }
})
const initFormvalue = {
    demandName: '',
    priorityLevel: '',
    description: ''
}
const subscriptFormRef:any=ref()
const addMetricsRef:any=ref()
const defaultFormData: {
  detailList: Array<{ value: MetricsFormI }>;
} = {
  detailList: [
    {
      value: {
        demandName: undefined,
        metricsLevel: undefined,
        description: undefined,
        supportDimension: undefined,
        remarks: undefined,
        timePeriod: undefined
      }
    }
  ]
};
const emit = defineEmits(['editSuccess', 'createdSuccess']);
const tabsFormRef:any = ref()
const formData = reactive({
  detailList: defaultFormData.detailList.concat([])
});

// 添加指标tab时首先需要校验
const onHandleAdd = async () => {
  const tabsErr = await tabsFormRef.value.validate()
  if (tabsErr) return;
  formData.detailList.push({
        value: {
          demandName: undefined,
          metricsLevel: undefined,
          description: undefined,
          supportDimension: undefined,
          remarks: undefined,
          timePeriod: undefined,
      }
  })
};
const onHandleDelete = (key:any) => {
  if (formData.detailList.length > 1) {
    formData.detailList.splice(key, 1);

  }
};

// 取消抽屉
const handleCancle = ()=>{
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '确定取消吗？',
    content: '取消后所填信息将被清空',
    simple: false,
    closable: true,
    okText: '确定',
    okButtonProps: {
      style: {
        backgroundColor: '#3C6EFF'
      }
    },
    onBeforeOk: (done) => {
      formData.detailList = cloneDeep(defaultFormData.detailList)
      subscriptFormRef.value.resetField()
      tabsFormRef.value.resetFields()
      visible.value = false
      done(true);
    }
  });
}
// 编辑提交
const editSubmit = async(params:any) => {
  const { code, msg } = await API.demand.postUpdate({
    ...params
  });
  if (code === 200) {
    visible.value = false
    emit('editSuccess')
    Message.success('编辑成功')
  }
}
// 创建提交
const createdSubmit = async (params:any) => {
  try {
    
    const { code } = await API.demand.postCreate({
      ...params
    });
    if (code === 200) {
      emit('createdSuccess')

      visible.value = false
      Message.success('创建成功')
      
    }
  } catch (error) {
    console.log('error: ', error);
  }
}
// 提交审核和暂存
const handleSubmit = debounce( async (status: any) => {

  const err = await subscriptFormRef.value.publishFormValids();
  const tabsErr = await tabsFormRef.value.validate()
  let detailList = formData.detailList?.map(
    (item:any) => {
      return {
        ...item.value,
      }
    }
  )
  detailList = detailList?.map((sItem:any) => {
    return {
      ...sItem,
      supportDimension: sItem?.supportDimension?.join(','),
      timePeriod: sItem?.timePeriod.join(','),
    }
  })
  if (err || tabsErr) {
    return
  }
  
  const params = {
    ...formValue.value,
    detailList,
    status,
    id: props?.editData?.id || ''
  };
  if (params.id) {
    editSubmit(params)
  } else {
    delete params.id
    createdSubmit(params)

  }
}, 2000, {
    'leading': true,
    'trailing': false
})
const visibleFn = () => {
    initData()
    visible.value = true
}

const initData = () => {
  formData.detailList = cloneDeep(defaultFormData.detailList)
  formValue.value = cloneDeep(initFormvalue)
}
defineExpose({
    visibleFn
})

watch(
  () => props.editData,
  (val) => {
    if (val) {
      const {priorityLevel, demandName, description, detailList} = val
      formValue.value = { priorityLevel,demandName,description }
      formData.detailList = detailList?.map(
        (item:any) =>{
          return {
            value: item
          }
        }
      )
    }
  }
)
</script>

<template>
    <a-drawer 
        :visible="visible" 
        @cancel="() => {
          initData()
          visible = false
        }" 
        :esc-to-close = "false"
        :mask-closable="false"
        placement="right"
        width="573px"
        unmountOnClose>
        <template #title>
          <div class="fw">{{props.title}}</div>
        </template>
        <div class="create-demand-wrapper">
          <DemandForm
            ref="subscriptFormRef"
            v-model="formValue.value"
          ></DemandForm>
          <a-form 
              :model="formData" 
              ref="tabsFormRef"
              auto-label-width
          >
            <ATabsCard 
              :formList="formData.detailList"
              :editable = "formData.detailList.length > 1 ? true : false"
              :isHasExtra="true"
              @handleAdd="onHandleAdd"
              @handleDelete="onHandleDelete"
            >
              <template #content="{item, index}">
                <div class="add-card-metrics">
                  <AddMetricsDemand 
                    ref="addMetricsRef"
                    v-model="item.value"
                    :fieldPath="`detailList.${index}.value`"
                  />
                </div>
              </template>
            </ATabsCard>
          </a-form>
        </div>
        <template #footer>
          <a-button @click="handleCancle">取消</a-button>
          <a-button @click="handleSubmit('10')">暂存</a-button>
          <a-button type="primary" @click="handleSubmit('20')">提交审核</a-button>
        </template>
    </a-drawer>
</template>

<style lang="scss" scoped>
@import './index.scss';
.create-demand-wrapper :deep(.arco-tabs-type-card-gutter > .arco-tabs-content) {
  border: none;
  .arco-tabs-content-item {
    background: #F6F8FC;
    border-radius: 3px;
    // padding: 18px 18px 0;
  }
}
.create-demand-wrapper :deep(.arco-tabs-nav-type-card-gutter .arco-tabs-tab) {
  text-align: center;
  line-height: 34px;
}

</style>